<template>
    <div class="search_container">
      <el-form inline>
        <el-form-item label="职位">
          <el-input  placeholder="输入角色名" v-model="roleName"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click='handleSearch'>搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table_container">
      <el-button type="primary" @click="isShowAddOrUpdateDialog = true; addOrUpdate = true">添加职位</el-button>
      <el-table :data="tableData" style="width: 100%; margin-top: 20px;" border height="300px" v-loading="loading">
        <el-table-column align="center" label="#" width="180">
          <template #default="scope">
            <span>{{  (currentPage-1)*pageSize+1+scope.$index }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="id" label="ID" width="180" />
        <el-table-column align="center" prop="roleName" label="职位名称" />
        <el-table-column align="center" prop="createTime" label="创建时间" show-overflow-tooltip />
        <el-table-column align="center" prop="updateTime" label="更新时间" show-overflow-tooltip />
        <el-table-column align="center" label="操作" width="300">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleClickAssignRole(scope.row.id)">分配权限</el-button>
            <el-button
                size="small"
                type="primary"
                @click="isShowAddOrUpdateDialog = true;  addOrUpdate = false; rowId = scope.row.id; form.roleName = scope.row.roleName"
            >编辑</el-button>
            <el-popconfirm title="请问确认删除吗？" @confirm="handleDelete(scope.row.id)">
              <template #reference>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          layout="prev, pager, next, total"
          :total="total"
          @current-change="handleCurrentChange"
      />

      <!--   新增与修改对话框   -->
      <el-dialog
          v-model="isShowAddOrUpdateDialog"
          :title="addOrUpdate ? '新增':'修改'"
          width="500"
          :before-close="handleClose"
          :show-close="false"
          :center="true"
      >
        <el-form style="display: flex; justify-content: center" :model="form" :rules="rules" ref="addAndUpdateForm" inline>
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="form.roleName" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" v-show="addOrUpdate" @click="handleAddRole">新增</el-button>
            <el-button type="primary" v-show="!addOrUpdate" @click="handleUpdateRole">修改</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

      <!-- draw -->
      <el-drawer
          v-model="drawerFlag"
          title="菜单列表"
      >
        <el-tree
            ref="menuTree"
            v-loading="menuLoading"
            style="max-width: 600px;"
            :default-expanded-keys="[1]"
            :default-checked-keys="checkedItem"
            :data="arrMenuData"
            show-checkbox
            node-key="id"
            :props="defaultProps"
        />
        <template #footer>
          <div style="flex: auto">
            <el-button type="primary" @click="handleConfirmUpdate">提交修改</el-button>
          </div>
        </template>
      </el-drawer>
    </div>
</template>

<script>
import {defineComponent, onMounted, ref} from "vue"
import {
  addRole,
  deleteRole,
  getAllSystemRoles,
  getMenuByRoleId,
  updateRole,
  updateTheRoleMenuPermission
} from "@/api/auth/role/index"
import {ElMessage} from "element-plus";

export default defineComponent({
    name: "role",
    setup() {
      const tableData = ref([]) // 表格的数据
      let currentPage = ref(1)
      let pageSize = ref(3)
      let total = ref(1)
      let loading = ref(false)
      let roleName = ref('')
      let addAndUpdateForm = ref()
      let isShowAddOrUpdateDialog = ref(false)
      let addOrUpdate = ref(true) // 新增或修改的标志，false --  修改、true --- 新增
      const form = ref({ roleName: '' })
      const rowId = ref()
      const drawerFlag = ref(false)

      // 规则
      const rules = ref({
        roleName: [
          { required: true, trigger: 'blur', message: '哥，必填' },
          {
            validator: (rule, value, callback) => {
              if (/\d/.test(value)) {
                callback("有数字，干哈呢")
              } else {
                callback()
              }
            },
          },
        ]
      })

      const getTableData = (data) => {
        // page limit
        loading.value = true
        getAllSystemRoles(data).then((res) => {
          if(res.code === 200) {
            tableData.value = res.data.records
            total.value = res.data.total
          }
          loading.value = false
        })
      }

      onMounted(() => {
        getTableData({ page: 1, limit: 3 })
      })

      const handleCurrentChange = () => {
        getTableData({ page: currentPage.value, limit: pageSize.value })
      }

      const handleSearch = () => {
        getTableData({ page: 1, limit: pageSize.value, roleName: roleName.value })
      }

      // 点击新增按钮
      const handleAddRole = () => {
        addAndUpdateForm.value.validate((valid) => {
          if(valid) {
            addRole({ roleName: form.value.roleName }).then((res) => {
              if(res.code === 200) {
                ElMessage({
                  message: "添加成功",
                  type: "success",
                }) // 提示成功
              } else {
                ElMessage({
                  message: "添加失败",
                  type: "error",
                }) // 提示失败
              }
              form.value.roleName = ""
              addAndUpdateForm.value.clearValidate('roleName')
              isShowAddOrUpdateDialog.value = false // 关闭
              getTableData({ page: 1, limit: 3 }) // 查询
              currentPage.value = 1
            })
          }
        })
      }

      // 关闭弹窗时清空表单元素
      const handleClose = (done) => {
        addAndUpdateForm.value.resetFields() // 置空
        done()
      }

      const handleUpdateRole = () => {
        addAndUpdateForm.value.validate((valid) => {
          if(valid) {
            updateRole({ roleName: form.value.roleName, id: rowId.value }).then((res) => {
              if(res.code === 200) {
                ElMessage({
                  message: "修改成功",
                  type: "success",
                }) // 提示成功
              } else {
                ElMessage({
                  message: "修改失败",
                  type: "error",
                }) // 提示失败
              }
              form.value.roleName = ""
              addAndUpdateForm.value.clearValidate('roleName')
              isShowAddOrUpdateDialog.value = false // 关闭
              getTableData({ page: currentPage.value, limit: 3 }) // 查询
            })
          }
        })
      }

      const arrMenuData = ref([])
      const menuLoading = ref(false)
      const defaultProps = ref({
        children: 'children',
        label: 'name',
      })
      const checkedItem = ref([]) // 默认勾选的菜单项
      let menuTree = ref()

      // 遍历出已勾选的菜单元素
      const temArr = [] // 存储id
      function filterLastLevelMenuItem(arr) {
        for (let i = 0; i < arr.length; i++) {
          if(arr[i].children && arr[i].children.length > 0) {
            filterLastLevelMenuItem(arr[i].children)
          } else if(arr[i].select) {
            temArr.push(arr[i].id)
          }
        }
        return temArr
      }

      const handleClickAssignRole = (id) => {
        drawerFlag.value = true
        menuLoading.value = true
        rowId.value = id
        getMenuByRoleId(id).then((res) => {
          if(res.code === 200) {
            arrMenuData.value = res.data
            // 递归
            temArr.length = 0 // 重置数组
            checkedItem.value = filterLastLevelMenuItem(res.data) // 设置默认勾选
          }
          menuLoading.value = false
        })
      }

      // 修改角色的菜单事件
      const handleConfirmUpdate = () => {
        // console.log(menuTree.value.getCheckedKeys())
        // console.log(menuTree.value.getHalfCheckedKeys())
        const ids = menuTree.value.getCheckedKeys().concat(menuTree.value.getHalfCheckedKeys()) // 拼接
        updateTheRoleMenuPermission({
          roleId: rowId.value,
          permissionId: ids
        }).then((res) => {
          if(res.code === 200) {
            ElMessage({
              message: "修改成功",
              type: "success"
            }) // 提示成功
          } else {
            ElMessage({
              message: "修改失败",
              type: "error"
            }) // 修改失败
          }
          drawerFlag.value = false
          window.location.reload() // 浏览器刷新
        })

      }

      // 删除的事件
      const handleDelete = (id) => {
        deleteRole(id).then((res) => {
          if(res.code === 200) {
            ElMessage({
              message: "删除成功",
              type: "success"
            })
          } else {
            ElMessage({
              message: "删除失败",
              type: "error"
            })
          }
          let page
          if(tableData.value.length > 1) {
            page = currentPage.value
          } else if(currentPage.value === 1){
            page = 1
          } else {
            page = currentPage.value - 1
          }
          getTableData({ page: page, limit: 3 }) // 查询
        })
      }


      return {
        tableData,
        currentPage,
        total,
        handleCurrentChange,
        loading,
        pageSize,
        roleName,
        handleSearch,
        isShowAddOrUpdateDialog,
        form,
        rules,
        addAndUpdateForm,
        addOrUpdate,
        handleAddRole,
        handleClose,
        handleUpdateRole,
        rowId,
        handleClickAssignRole,
        drawerFlag,
        arrMenuData,
        defaultProps,
        menuLoading,
        checkedItem,
        handleConfirmUpdate,
        menuTree,
        handleDelete

      }
    },
})
</script>

<style scoped lang="scss">

</style>
